package com.ltf.springframework.support;

import com.ltf.springframework.beans.BeanDefinition;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class BeanDefinitionReader {

    private Properties config = new Properties();

    private List<String> beanNames = new ArrayList<>();

    public BeanDefinitionReader(String... configLocations) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(configLocations[0].replace("classpath:",""));
        try {
            config.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 扫描包，将包下的类名存放在集合中
        doScanner(config.getProperty("package"));
    }



    private void doScanner(String packageName){
        String scannerFilePath = packageName.replaceAll("\\.", "/");
        // 获取该包下的资源
        URL url = this.getClass().getResource("/" + scannerFilePath);
        File file = new File(url.getFile());
        for (File f : file.listFiles()) {
            if (f.isDirectory()){
                doScanner(packageName+"."+f.getName());
            }else {
                beanNames.add(packageName+"."+f.getName().replace(".class",""));
            }
        }


    }

    public List<String> loadBeanDefinition() {
        return this.beanNames;
    }

    public BeanDefinition registyBean(String beanName) {
        BeanDefinition beanDefinition = new BeanDefinition();
        beanDefinition.setClassName(beanName);
        beanDefinition.setFactoryBeanName(firstToLower(beanName.substring(beanNames.lastIndexOf(".") + 1)));
        return beanDefinition;
    }

    private String firstToLower(String beanName){
        char[] chars = beanName.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }
}
